<template>
    <el-container class="goods-index-main">
        <el-header class="sa-header">
            <div class="sa-title sa-flex sa-row-between">
                <div class="label sa-flex">
                    <span class="left sa-flex"><el-icon @click="back" class="sa-m-r-10"><ArrowLeft /></el-icon>{{ route.query.type=='view'?'选品库商品':'添加选品' }}</span>

                    <search-condition :conditionLabel="filterParams.conditionLabel"
                        @deleteFilter="deleteFilter"></search-condition>
                </div>
                <!-- <div>
                    <el-button class="sa-button-refresh" icon="Search" @click="openFilter"></el-button>
                </div> -->
            </div>
            <div class="params">
                <div class="title sa-m-b-20">商品分类</div>
                <div class="classicifi sa-flex">
                    <el-cascader v-if="name === '1688'" ref="cascaderRef" style="width: 400px;margin-right: 10px;" :persistent="persistent"
                        :options="firstLevel" placeholder="请选择商品分类" :show-all-levels="false" :props="propsqd" clearable
                        v-model="store.form.value1" @change="handleChange" @visible-change="handleVisibleChange" />
                    <el-cascader v-else ref="cascaderRef" style="width: 400px;margin-right: 10px;" :persistent="persistent"
                        :options="firstLevel" placeholder="请选择商品分类" :show-all-levels="false" :props="props" clearable
                        v-model="store.form.value1" @change="handleChange" @visible-change="handleVisibleChange"/>
                    <el-input v-if="name !== '1688'" placeholder="请输入商品ID" v-model="store.form.goodsSkuCode" class="sa-m-l-10 sa-w-200"></el-input>
                    <el-input placeholder="请输入关键字" v-model="store.form.goodsSkuName" class="sa-m-l-10 sa-w-200"></el-input>
                    <el-button v-if="route.query.type!=='view'" class="sa-button-add sa-m-l-20" @click="getData(pageData.page)">搜 索</el-button>
                </div>
            </div>
        </el-header>
        <el-main class="sa-p-0" v-loading="store.loading">
            
            <el-table v-if="name !== '1688'" height="100%" class="sa-table sa-m-t-20" :data="store.tableData"
            @selection-change="changeSelection" stripe>
                <template #empty>
                    <sa-empty></sa-empty>
                </template>
                <el-table-column type="selection" width="48" align="center"></el-table-column>
                <el-table-column sortable="custom" prop="goodsSkuCode" label="ID" min-width="140"></el-table-column>
                
                <el-table-column label="商品" min-width="440">
                    <template #default="scope">
                        <goods-item :goods="{
                            image: scope.row.main_img,
                            title: scope.row.brandName,
                            subtitle: scope.row.goodsSkuName,
                            activities: scope.row.activities,
                            promos: scope.row.promos,
                        }" mode="goods"></goods-item>
                    </template>
                </el-table-column>
                <el-table-column align="center" sortable="custom" prop="goodsUnit" label="单位" min-width="80"></el-table-column>
                <el-table-column sortable="custom" prop="sellPrice" label="供货价" min-width="150" align="center">
                    <template #default="scope">
                        <div>{{ scope.row.marketPrice }}</div>
                    </template>
                </el-table-column>
                <el-table-column sortable="custom" prop="sellPrice" label="销售价" min-width="100"
                    align="center"></el-table-column>
                <!-- <el-table-column label="库存" min-width="100" align="center">
                    <template #default="scope">
                        <div class="sa-flex sa-row-center stock">
                            <span>{{ scope.row.stock || 0 }}</span>
                            <el-button v-auth="'shop.admin.goods.goods.addstock'" class="add-stock" link>
                                <sa-icon name="sa-shop-goods-add-stock" @click="editStock(scope.row)" />
                            </el-button>
                        </div>
                    </template>
                </el-table-column> -->
                <!-- <el-table-column label="更新时间" width="172">
                    <template #default="scope">{{ scope.row.create_time || '-' }}</template>
                </el-table-column> -->
                <el-table-column label="操作" min-width="240" fixed="right" v-if="route.query.type !== 'view'">
                    <template #default="scope">
                        <div class="sa-flex">

                            <el-button v-if="scope.row.is_in == 0" v-auth="'shop.admin.goods.goods.detail'" class="is-link sa-m-l-12" type="primary"
                                @click="editRow(scope.row,true)">加入选品库</el-button>
                                <el-button v-else v-auth="'shop.admin.goods.goods.detail'" class="is-link sa-m-l-12" type="primary" disabled
                               >已加入选品库</el-button>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
            <el-table v-else height="100%" class="sa-table sa-m-t-20" :data="store.tableData"
                @selection-change="changeSelection" row-key="itemId" stripe>
                <template #empty>
                    <sa-empty></sa-empty>
                </template>
                <el-table-column type="selection" width="48" align="center"></el-table-column>
                <el-table-column sortable="custom" prop="itemId" label="ID" min-width="140"></el-table-column>
                
                <el-table-column label="商品" min-width="440">
                    <template #default="scope">
                        <goods-item :goods="{
                            image: scope.row.imgUrl,
                            title: scope.row.title,
                            subtitle: scope.row.goodsSkuName,
                            activities: scope.row.activities,
                            promos: scope.row.promos,
                        }" mode="goods"></goods-item>
                    </template>
                </el-table-column>
                <!-- <el-table-column align="center" sortable="custom" prop="goodsUnit" label="单位" min-width="80"></el-table-column> -->
                <el-table-column sortable="custom" prop="sellPrice" label="供货价" min-width="150" align="center">
                    <template #default="scope">
                        <!-- <div>{{ scope.row.maxPrice / 100 }} 元</div> -->
                        <div v-if="scope.row.minPrice === scope.row.maxPrice">{{ scope.row.minPrice / 100 }}</div>
                        <div v-else>{{ scope.row.minPrice / 100 + ' ~ ' + scope.row.maxPrice / 100 }}</div>
                    </template>
                </el-table-column>
                <!-- <el-table-column sortable="custom" prop="sellPrice" label="销售价" min-width="100"
                    align="center"></el-table-column> -->
                <!-- <el-table-column label="库存" min-width="100" align="center">
                    <template #default="scope">
                        <div class="sa-flex sa-row-center stock">
                            <span>{{ scope.row.stock || 0 }}</span>
                            <el-button v-auth="'shop.admin.goods.goods.addstock'" class="add-stock" link>
                                <sa-icon name="sa-shop-goods-add-stock" @click="editStock(scope.row)" />
                            </el-button>
                        </div>
                    </template>
                </el-table-column> -->
                <!-- <el-table-column label="更新时间" width="172">
                    <template #default="scope">{{ scope.row.create_time || '-' }}</template>
                </el-table-column> -->
                <el-table-column label="操作" min-width="240" fixed="right" v-if="route.query.type !== 'view'">
                    <template #default="scope">
                        <div class="sa-flex">
                            <el-button class="is-link sa-m-l-12" type="primary"
                            @click="openwindow(scope.row)">查看商品链接</el-button>
                            <el-button v-auth="'shop.admin.goods.goods.detail'" class="is-link sa-m-l-12" type="primary"
                                @click="editRow(scope.row,true)" v-if="scope.row.status === 1">加入选品库</el-button>
                                <el-button v-else v-auth="'shop.admin.goods.goods.detail'" class="is-link sa-m-l-12" type="primary" disabled
                               >已加入选品库</el-button>
                               
                        </div>
                    </template>
                </el-table-column>
            </el-table>
        </el-main>
        <el-footer class="goods-index-footer">
      <sa-view-bar>
        <template #left>
            <el-button v-if="route.query.type!=='view'" class="sa-button-add sa-m-l-20" @click="bathAddGoods">批量选品</el-button>
        </template>
        <template #right>
          <sa-pagination :pageData="pageData" @updateFn="getData" :pagesize="[10,20]" />
        </template>
      </sa-view-bar>
    </el-footer>
        <!-- <sa-view-bar>
            <template #right>
                <sa-pagination :pageData="pageData" @updateFn="getData" />
            </template>
        </sa-view-bar> -->
    </el-container>
</template>
<script>
export default {
    name: 'supplychian.admin.goods.store.addgoods',
};
</script>

<script setup>
import { onMounted, reactive, ref, computed, nextTick } from 'vue';
import { usePagination, useModal } from '@/sheep/hooks';
import { api } from '../goods.service';
import { useSearch } from '@/sheep/components/sa-table/sa-search/useSearch';
import { cloneDeep } from 'lodash';
import { ElMessage } from 'element-plus';
import $storage from '@/sheep/utils/storage';
import GoodsItem from '../components/goods-item.vue';
import { useRoute } from 'vue-router';
import router from '@/sheep/router';
const route=useRoute()
const cascaderRef = ref(null)
const props = {
    lazy: true,
    checkStrictly: true,
    async lazyLoad(node, resolve) {
        searchParams.level = node.level + 1
        searchParams.categoryCode = node.value || ""
            const { error, data } = await api.getGoodsClass(searchParams);
            const nodes = data.map((item) => {
                return {
                    label: item.categoryName,
                    value: item.categoryCode,
                    children: [],
                    leaf: node.level >= 2
                };
            });
            resolve(nodes);
        
    },
}
const propsqd = {
    lazy: true,
    checkStrictly: true,
    async lazyLoad(node, resolve) {
        console.log('node',node)
        searchParams.level = node.level + 1
        searchParams.categoryID = node.value || ""
            const res = await api.shopcategory(searchParams);
            const nodes = res.categoryInfo[0].childCategorys.map((item) => {
                return {
                    label: item.name,
                    value: item.id,
                    children: [],
                    // leaf: node.categoryLevel >= 2
                    // leaf: true
                    leaf: item.isLeaf
                };
            });
            resolve(nodes);
        
    },
}
const back=()=>{
    router.back(1)
}
const openwindow = (item) => {
    window.open(`https://detail.1688.com/offer/${item.itemId}.html`)
}
const handleChange = (value, node, extra) => {
    console.log('onChange', value, node, extra);
    cascaderRef.value?.togglePopperVisible(false);
    searchParams.categoryCode=value[value.length - 1]
    getData(1)
};
const getRowKey = (row) => {
  return row.itemId;
};
const editRow =async(row,type)=>{
    if(name.value === '1688'){
        if(row){
            searchParams.goodsCodes.push(row.goodsCode)
        }
        let data = [row]
        if(!type){
            data = store.selected
        }
        data.forEach(item=>{
            item.cid = searchParams.house_id
            if(item.serviceList.length > 5){
                item.serviceList = item.serviceList.slice(0, 5)
            }
        })
        const { error, msg } = await api.shopadd_my_goods(data)
        if(error==0){
            ElMessage.success('加入选品库成功')
        }
        else{
            ElMessage.error(msg)
        }
        getData()
    }else{
        let list = []
        if(row){
            list.push(row.goodsSkuCode)
        }else{
            store.selected.forEach(item=>{
                list.push(item.goodsSkuCode)
            })
        }
        // searchParams.goodsCodes.push(row.goodsCode)
        const { error, data } = await api.addGoods({
            goodsSkuCode:list,
            house_id: route.query.id
        })
        
        if(error==0){
            ElMessage.success('加入选品库成功')

        }
        else{
            ElMessage.error('加入选品库失败')
        }
        getData()
    }
    
}
const firstLevel = ref([])
const secondLevel = ref([])
const thirdLevel = ref([])
const fourthLevel = ref([])
const store = reactive({
    loading: false,
    tableData: [],
    selected: [],
    form: {
    },
});
const searchParams = reactive({
    level: 1,
    categoryCode:"",
    house_id:"",
    goodsCodes:[]
})
// const getNextlevel = async (level) => {
//     searchParams.level = level
//     if (level == 2) {
//         searchParams.categoryCode = store.form.value1
//         getGoodsType()
//     }
//     if (level == 3) {
//         searchParams.categoryCode = store.form.value2
//         getGoodsType()
//     }
//     if (level == 4) {
//         searchParams.categoryCode = store.form.value3
//         getGoodsType()
//     }
// }

// // 获取商品分类
// const getGoodsType = async () => {
//     const { error, data } = await api.getGoodsClass(searchParams);
//     console.log(error, data, '获取的数据');
//     if (data[0].categoryLevel == 1) {
//         firstLevel.value = data.map(el => {
//             return {
//                 label: el.categoryName,
//                 value: el.categoryCode
//             }
//         })

//     }
//     else if (data[0].categoryLevel == 2) {
//         secondLevel.value = data.map(el => {
//             return {
//                 label: el.categoryName,
//                 value: el.categoryCode
//             }
//         })
//     }
//     else if (data[0].categoryLevel == 3) {
//         thirdLevel.value = data.map(el => {
//             return {
//                 label: el.categoryName,
//                 value: el.categoryCode
//             }
//         })
//     }
//     else if (data[0].categoryLevel == 4) {
//         fourthLevel.value = data.map(el => {
//             return {
//                 label: el.categoryName,
//                 value: el.categoryCode
//             }
//         })

//     }

// };
// table 批量选择
function changeSelection(row) {
    console.log('row',row)
    store.selected = row;
}
// 批量入库
const bathAddGoods = () => {
    if (store.selected.length == 0) {
        ElMessage.error('请选择选入商品库的商品');
    }
    else{
        searchParams.goodsCodes=store.selected.map(el=>el.goodsSkuCode)
        // console.log(searchParams);
        editRow()
    }
}

const filterParams = reactive({
    tools: {
        handle_name: {
            type: 'tinput',
            label: '供应商ID/供应商名称',
            field: 'handle_name',
            value: '',
        },
        status: {
            type: 'tselect',
            label: '请选择供应商',
            field: 'status',
            multiple: true,
            value: [],
            options: {
                data: [
                    {
                        label: '全部',
                        value: '',
                    },
                    {
                        label: '待提交',
                        value: '-1',
                    },
                    {
                        label: '已退回',
                        value: '0',
                    },
                    {
                        label: '待办理',
                        value: '2',
                    },
                    {
                        label: '办理中',
                        value: '3',
                    },
                    {
                        label: '已完结',
                        value: '4',
                    },
                    {
                        label: '已退款',
                        value: '5',
                    },
                ],
            },
        },
    },
    data: {
        handle_name: '',
        status: [],
    },
    conditionLabel: {},
});
const { openFilter, deleteFilter } = useSearch({ filterParams, getData });

const { pageData } = usePagination();

async function getData(page) {
    store.loading = true
    if (page) pageData.page = page;
    if(name.value === '1688'){
        const res = await api.shopgood_list({
            page: pageData.page,
            limit: pageData.list_rows,
            keyword: store.form.goodsSkuName,
            categoryId:searchParams.categoryCode
            // categoryCode: searchParams.categoryCode,
            // 'categoryId':searchParams.house_id
        });
            store.tableData = res.result.result;
            pageData.page = res.result.pageInfo.currentPage;
            pageData.list_rows = res.result.pageInfo.pageSize;
            pageData.total = res.result.pageInfo.totalRecords;
    }else{
        console.log('pageData',pageData)
        const { error, data } = await api.goodList({
            pageNum: pageData.page,
            pageSize: pageData.list_rows,
            categoryCode: searchParams.categoryCode,
            'house_id':searchParams.house_id,
            goodsSkuName:store.form.goodsSkuName,
            goodsSkuCode:store.form.goodsSkuCode,
        });
        if (error === 0) {
            store.tableData = data.data;
            pageData.page = data.current_page;
            pageData.list_rows = data.per_page;
            pageData.total = data.totalCount;
        }
    }
    store.loading = false
    
}
const name = ref('')
onMounted(() => {
    if ($storage.get('lastLogin').info.merchant_id) {
        delete filterParams.tools.assign_status;
    }
    searchParams.house_id = route.query.id
    name.value = route.query.name
    getData();
    // getGoodsType()
});

const handleVisibleChange = (visible) => {
  if (visible) {
    nextTick(() => {
      // 查找所有级联菜单的滚动容器
      const menuWraps = document.querySelectorAll('.el-cascader-menu__wrap');
      menuWraps.forEach(wrap => {
        wrap.style.height = '550px'; // 设置固定高度
        wrap.style.maxHeight = 'none'; // 移除最大高度限制
      });
    });
  }
};
</script>
<style lang="scss" scoped></style>